package com.miao.im.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.miao.im.filter.WebAuthInterceptor;
import com.miao.im.support.FastJsonConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/4/12 21:57
 * @Description:
 */
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
    @Autowired
    private WebAuthInterceptor webAuthInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(webAuthInterceptor)
                .addPathPatterns("/**");
    }

    /**
     * 配置跨域
     * @author miaoguoxin
     * @date 2020/8/11
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("POST","GET","PUT","OPTIONS","DELETE")
                .allowedHeaders("*")
                .maxAge(3600)
                .allowCredentials(true);
    }


    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        Iterator it =  converters.iterator();
        int index = -1;
        int tmp = 0;
        while (it.hasNext()){
            Object obj = it.next();
            //去掉MappingJackson2HttpMessageConverter
            if(obj instanceof MappingJackson2HttpMessageConverter){
                it.remove();
                index = tmp;
            }
            if(index == -1) {
                tmp++;
            }
        }
        FastJsonConverter fastJsonConverter = new FastJsonConverter();
        //将FastJsonHttpMessageConverter加在MappingJackson2HttpMessageConverter的位置，比xml解析器靠前，以提升性能
        if(index != -1){
            converters.add(index, fastJsonConverter);
        }
        //如果没有MappingJackson2HttpMessageConverter，还是要在最后加上FastJsonHttpMessageConverter
        else {
            converters.add(fastJsonConverter);
        }
    }
}
